package cn.tedu.v7;

import com.sun.xml.internal.ws.api.model.wsdl.WSDLOutput;
import jdk.nashorn.internal.objects.Global;

import java.io.*;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;

/**
 * 程序关闭
 */
public class Server {
    private ServerSocket serverSocket;
    private static final Integer PORT=6666;
    private List<PrintWriter> allOut=new ArrayList<>();
    private Set<String> onlineUsers=new HashSet<>();
    private Map<String,String> userDataBase;


    public Server() {
        try {
            serverSocket = new ServerSocket(PORT);
            userDataBase=new HashMap<>();
            userDataBase.put("哈阳","123456");
            userDataBase.put("杨哈哈","654321");
        } catch (BindException e) {
            System.out.println("端口号重复出申请，建议换个端口号");
        } catch (IOException e) {
            System.out.println("申请端口号失败....");
        }
    }
    public void start() {
        try {
            while (true) {

                System.out.println("----等待客户端链接-----");
                Socket socket = serverSocket.accept();
                new Thread(new ClientHandler(socket)).start();
            }
        } catch (IOException e) {
            System.out.println("服务器端通讯断开了");
        } finally {
            if (serverSocket != null && !serverSocket.isClosed()) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    System.out.println("服务器关闭失败");
                }
                System.out.println("服务器关闭成功--ok");
            }

        }

    }

    public static void main(String[] args) {new Server().start();}

    private synchronized void broadcastMessage(String message){
        for (PrintWriter pw: allOut){
            pw.println("消息广播："+message);
        }
    }

  /*  public void setAllOut(List<PrintWriter> allOut) {
        this.allOut = allOut;   ??这是要设置写出方法？？
    }*/

    private synchronized void updateOnlineUsers(){
        System.out.println("测试--------------是否进入方法");
        String userList="在线用户："+String.join(",",onlineUsers);
        for (PrintWriter pw:allOut){//遍历给所有客户端
       //     System.out.println(userList);
            pw.println(userList);  //打印用户名信息
        }
    }

//            userList="在线用户："+String.join("，",onlineUsers);  //这里正确
//            System.out.println(userList);
//            broadcastMessage(userList);   这里你是需要打印给客户端的，需要用写出流  pw.println(userList);




    private class ClientHandler implements Runnable {
        private String username;
        private String password;
        private Socket socket;
        private String ip;
        private BufferedReader br;
        private PrintWriter pw;

        public ClientHandler(Socket s) {
            this.socket = s;
            ip = socket.getInetAddress().getHostAddress();
            try {
                 br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF8"));
                 pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8")), true);
                synchronized (allOut) {
                    allOut.add(pw);
                }

            } catch (IOException e) {
                System.out.println("客户端断开链接~~");
            }
        }
        private boolean Login(String user,String pass){
            return userDataBase.containsKey(user)&&userDataBase.get(user).equals(pass);
        }
        private void handlerChat(){
            new Thread(() -> {
                String message;
                try {
                    while ((message = br.readLine()) != null) {
                        System.out.println("客户端说：" + message);
                        System.out.println("服务器端请输入：");
                        broadcastMessage(message);
                    }
                } catch (IOException e) {
                    System.out.println("客户端读入失败");
                }
            }).start();
            Scanner input = new Scanner(System.in);
            while (true) {
                System.out.println("服务器请输入");
                String say = input.nextLine();
                pw.println("服务器说：" + say);


                    if (say.equalsIgnoreCase("exit")){
                  ///      System.exit(0);  // 这里错了，服务器端不能退出，退出之后其他客户端怎么链接？？  需要break;跳出
                        break;
                    }
                }

        }
        public void run() {
            try {
                pw.println("请输入用户名：");
                username=br.readLine();
                pw.println("请输入密码");
                password=br.readLine();
                  if (Login(username,password)) {
                      pw.println("登陆成功，欢迎进入聊天室");
                      onlineUsers.add(username);
                      synchronized (onlineUsers){
                          updateOnlineUsers();
                      }
                      handlerChat();
                      updateOnlineUsers();
                  }else {
                      pw.println("登陆失败，用户名或密码错误");
                      socket.close();
                  }
            } catch (NullPointerException e) {
                System.out.println("IO 流传入对象，" +
                        "有对象为null!立马核对，" +
                        "建议：查看try块中对象可能赋值为null");
            } catch (IOException e){
                System.out.println("服务器端断开连接");
            }
            finally {
                synchronized (onlineUsers){
                    onlineUsers.remove(username);
                }
                synchronized (allOut) {
                    allOut.remove(pw);
                }

                if (br!= null)
                    try {
                        br.close();
                    } catch (IOException e) {
                        System.out.println("结束通讯：关闭失败！");
                    }
                if (pw!=null) pw.close();
                if (socket != null && !socket.isClosed()) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        System.out.println("通讯关闭失败");
                    }
                }
            }

        }

    }
}